package com.android.driveuploader;

/**
 * Created by srikanthg on 8/27/14.
 */
import android.content.Context;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * A fetcher for thumbnail urls from a given picasa REST api url.
 */
public class ImageUrlFetcher {

    /**
     * Callback to be called. Help! I need a better comment!
     */
    public interface Callback {
        void onResult(List<String> urls);
        void onError(Exception e);
    }

    private final Context context;

    public ImageUrlFetcher(Context context) {
        this.context = context;
    }

    /**
     * Fetches the content of the url on a background thread. Callback methods are invoked on the UI
     * thread.
     */
    public void fetch(final String url, final Callback callback) {
        JsonObjectRequest request = new JsonObjectRequest(
                Request.Method.GET,
                url,
                null /* jsonRequest */,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            callback.onResult(parse(jsonObject));
                        } catch (JSONException e) {
                            callback.onError(e);
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        callback.onError(volleyError);
                    }
                });

        request.setTag(context);
        VolleyUtils.getRequestQueue(context).add(request);
    }

    private List<String> parse(JSONObject response) throws JSONException {
        JSONArray entries = response.getJSONObject("feed").getJSONArray("entry");
        List<String> result = new ArrayList<String>();
        for (int i = 0; i < entries.length(); i++) {
            JSONObject picture = entries.getJSONObject(i);
            JSONObject pictureData = (JSONObject) picture.getJSONObject(
                    "media$group").getJSONArray("media$thumbnail").get(0);
            result.add(pictureData.getString("url"));
        }
        return result;
    }
}
